package com.qdu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/register")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        JsonObject jsonResponse = new JsonObject();

        try {
            JsonObject jsonRequest = JsonParser.parseReader(request.getReader()).getAsJsonObject();
            String username = jsonRequest.get("username").getAsString();
            String password = jsonRequest.get("password").getAsString();

            // JDBC URL, username and password of MySQL server
            String url = "jdbc:mysql://localhost:3306/yourdatabase"; // 修改为你的数据库URL
            String user = "yourusername"; // 修改为你的数据库用户名
            String dbPassword = "yourpassword"; // 修改为你的数据库密码

            // Opening database connection
            Connection conn = DriverManager.getConnection(url, user, dbPassword);

            // Checking if the user exists
            String checkUserQuery = "SELECT password FROM users WHERE username = ?";
            PreparedStatement pstmt = conn.prepareStatement(checkUserQuery);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (!rs.next()) {
                jsonResponse.addProperty("status", "no_user");
            } else {
                String storedPassword = rs.getString("password");
                if (!storedPassword.equals(password)) {
                    jsonResponse.addProperty("status", "wrong_password");
                } else {
                    jsonResponse.addProperty("status", "success");
                }
            }

            rs.close();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            jsonResponse.addProperty("status", "error");
            jsonResponse.addProperty("message", e.getMessage());
        }

        out.print(jsonResponse.toString());
        out.flush();
    }
}
